﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SensorSimFSI
{
    class MakeMsg
    {
        //Position inst-area
        public static byte		VERSION		=		0;

        public static byte LEN_OF_INST = 1;
        public static byte LEN_OF_RESPONSE = 1;

        public static byte ADDR_DES_L = 2;
        public static byte ADDR_DES_H = 3;
        public static byte ADDR_SRC_L = 4;
        public static byte ADDR_SRC_H = 5;
        public static byte PROPERTY = 6;
        public static byte OPERATION = 7;
        public static byte PARA1 = 8;
        public static byte PARA2 = 9;
          //#define	bitMemoryReset 			0
          //#define	bitCalendarRefresh		1
          //#define	bitMemoryRstMode		2	//0: MODE_CALCULATE 	1: MODE_DOWNLOAD

        public static byte PARA3 = 10;
        public static byte PARA4 = 11;
        public static byte PARA5 = 12;
        public static byte PARA6 = 13;
        public static byte CRC_L = 14;
        public static byte CRC_H = 15;

        public static byte DATA0 = 16;
        public static byte lenHEAD = 16;

        public static int MakeProtocol(byte[] buf)  //, const char* fmt,...)
        {
            byte len,lenMsg;
    
            //clr buffer
	        FillBufWith(buf,64,0x0);

            //head
            buf[VERSION]='>';
        //  des[LEN_OF_INST]=78-1;  							//calculated length later
            buf[ADDR_DES_L]=0;
            buf[ADDR_DES_H]=0;
            buf[ADDR_SRC_L]=0;        
            buf[ADDR_SRC_H]=0;        
            buf[PROPERTY]=0;
            buf[OPERATION]=0;
            buf[PARA1]=0;
            buf[PARA2]=0;
            buf[PARA3]=0;
            buf[PARA4]=0;
            buf[PARA5]=0;
            buf[PARA6]=0;
        //  d[CRC_L]=LoOfInt(iCRC);
        //  d[CRC_H]=HiOfInt(iCRC);

            va_list ap;
            va_start(ap, fmt);
            len=vsprintf((char *)&buf[DATA0], fmt, ap);
            va_end(ap);

            lenMsg=DATA0+len+2;
            buf[LEN_OF_INST]=lenMsg-1;    	//2: length of CRC

            setMsgCrc(buf,lenMsg);
            return len;
        }

        void setMsgCrc(byte[] buf,byte lenMsg)
        {
            UInt16 iCRC;
            byte len;

        //CRC of header
            iCRC = GetCRC(buf, lenHEAD - 2);
            buf[CRC_L]=LoOfInt(iCRC);
            buf[CRC_H]=HiOfInt(iCRC);

        //CRC of DATA0
            len=lenMsg-DATA0-2;
            iCRC=GetCRC(&buf[DATA0],len);                  
            buf[DATA0+len]=LoOfInt(iCRC);
            buf[DATA0+len+1]=HiOfInt(iCRC);
        }

        UInt16 GetCRC(byte[] buf,UInt16 len)
        {
            UInt16 i;
            UInt16 sum;

            sum=0;
	        for(i=len;i!=0;i--){
	          sum+=buf[i];
	        }

            return -1-sum;
        }



    }
}
